package com.tutu.utils;

import com.google.gson.ExclusionStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tutu.utils.gson.DmsExclusionStrategy;
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import org.springframework.data.domain.Page;

import java.util.*;

/**
 * json工具类
 * Created by 涂奕恒 on 14-10-17.
 */
public class JsonUtil {

    public static String obj2Json(Object obj) {
        Gson gson = new GsonBuilder().serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        return gson.toJson(obj);
    }

    /**
     * java对象转换成json字符串
     */
    public static String obj2Json(Object obj, String... excludes) {
        ExclusionStrategy strategy = new DmsExclusionStrategy(excludes);
        Gson gson = new GsonBuilder().serializeNulls().setExclusionStrategies(strategy).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        return gson.toJson(obj);
    }

    /**
     * java对象转换成json字符串,过滤成api需要的字段值
     */
    public static String obj2ApiJson(Object obj, String... excludes) {
        /*String[] strings = new String[excludes.length + 1];
        System.arraycopy(excludes, 0, strings, 0, excludes.length);
        strings[excludes.length] = "updateTime";
        String json = obj2Json(obj, strings);*/
        return filterJson(obj2Json(obj, excludes));
    }

    /**
     * 过滤字符串 -> true转换成0，false转换成1,null转换成""或者{}
     */
    public static String filterJson(String json) {
        return json.replaceAll("\"image\":null", "\"image\":{}").replaceAll(":null", ":\"\"");
    }

    /**
     * 将json格式的字符串解析成Map对象
     */
    public static Map<String, Object> json2Map(Object object, String... excludeFields) {
        Set<String> excludes = new HashSet<>(Arrays.asList(excludeFields));
        Object parsed = parseJsonElement(JSONObject.fromObject(object), excludes);
        return (parsed instanceof Map) ? (Map<String, Object>) parsed : new HashMap<>();
    }

    /**
     * json转换公共类
     *
     * @param page 分页数据
     * @return
     */
    public static Map<String, Object> fitting(Page<?> page) {
        List<?> list = page.getContent();

        // data中的page
        Map<String, Object> pageMap = new HashMap<>();
        pageMap.put("totalNum", page.getTotalElements());
        pageMap.put("totalPage", page.getTotalPages());
        pageMap.put("currentPage", page.getNumber() + 1);

        // data中的list
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("list", list);
        dataMap.put("page", pageMap);
        return dataMap;
    }

    private static Object parseJsonElement(Object element, Set<String> excludes) {
        if (element instanceof JSONObject) {
            return parseJsonObject((JSONObject) element, excludes);
        } else if (element instanceof JSONArray) {
            return parseJsonArray((JSONArray) element, excludes);
        } else if (element instanceof JSONNull) {
            return null; // 处理空值
        }

        return element; // 基本类型直接返回
    }

    private static Map<String, Object> parseJsonObject(JSONObject jsonObj, Set<String> excludes) {
        Map<String, Object> result = new LinkedHashMap<>();

        for (Object key : jsonObj.keySet()) {
            String fieldName = key.toString();
            if (excludes.contains(fieldName)) continue; // 过滤字段

            Object value = jsonObj.get(fieldName);
            result.put(fieldName, parseJsonElement(value, excludes));
        }

        return result;
    }

    private static List<Object> parseJsonArray(JSONArray jsonArray, Set<String> excludes) {
        List<Object> result = new ArrayList<>();

        for (Object o : jsonArray) result.add(parseJsonElement(o, excludes));

        return result;
    }
}
